/**
 * pos.js - v-final-clean
 * 收银台页面核心脚本
 * 最终重构版，解决脚本结构和冲突问题
 */
document.addEventListener('DOMContentLoaded', function () {
    // --- 全局常量和变量 ---
    const BASE_URL = '';
    let allProducts = [];
    let shoppingCart = [];

    // --- DOM 元素缓存 ---
    const productInput = document.getElementById('barcode');
    const quantityInput = document.getElementById('quantity');
    const cartTableBody = document.getElementById('cartItems');
    const totalAmountEl = document.getElementById('totalAmount');
    const salesEl = document.getElementById('todaySales');
    const ordersEl = document.getElementById('todayOrders');
    const itemsEl = document.getElementById('todayItems');
    const membersEl = document.getElementById('memberOrders');
    const userInfoEl = document.getElementById('userInfo');
    const addToCartBtn = document.getElementById('addToCartBtn');
    const checkoutBtn = document.getElementById('checkoutBtn');
    const resetCartBtn = document.getElementById('resetCartBtn');

    // --- 核心功能：更新顶部统计卡片 ---
    async function updateStats() {
        console.log('[诊断] 1. 开始执行 updateStats 函数...');
        if (!salesEl) { console.error('[诊断] 错误: salesEl 未找到'); return; }

        salesEl.textContent = '0.00';
        ordersEl.textContent = '0';
        itemsEl.textContent = '0';
        membersEl.textContent = 'N/A';

        try {
            const response = await fetch(`${BASE_URL}/api/sale_getall`);
            if (!response.ok) throw new Error(`API请求失败`);
            
            const rawData = await response.json();
            const allSales = Array.isArray(rawData) ? rawData : (rawData.data || []);
            
            if (allSales.length === 0) { console.log('[诊断] 结论：无销售数据。'); return; }

            let latestDateString = '';
            for (const sale of allSales) {
                if (sale && sale.date && typeof sale.date === 'string' && sale.date.includes('T')) {
                    const currentDateString = sale.date.split('T')[0];
                    if (currentDateString > latestDateString) latestDateString = currentDateString;
                }
            }
            if (!latestDateString) { console.log('[诊断] 结论：未找到有效日期。'); return; }

            let totalSales = 0, totalOrders = 0, totalItems = 0;
            for (const sale of allSales) {
                if (sale.date?.startsWith(latestDateString)) {
                    totalSales += (sale.total_price ?? 0);
                    totalOrders++;
                    totalItems += (sale.amount ?? 0);
                }
            }
            console.log(`[诊断] 计算完成: 销售额=${totalSales}, 订单数=${totalOrders}, 商品数=${totalItems}`);

            salesEl.textContent = totalSales.toFixed(2);
            ordersEl.textContent = totalOrders;
            itemsEl.textContent = totalItems;
            console.log('[诊断] DOM更新完毕。');

        } catch (error) {
            console.error('[诊断] 错误：在 updateStats 函数执行期间发生严重错误:', error);
        }
    }
    
    // --- 业务逻辑函数 ---
    
    function renderCart() {
        cartTableBody.innerHTML = '';
        let total = 0;
        shoppingCart.forEach(item => {
            const subtotal = item.price * item.quantity;
            total += subtotal;
            const row = document.createElement('tr');
            
            const deleteBtn = document.createElement('button');
            deleteBtn.textContent = '删除';
            deleteBtn.onclick = () => removeFromCart(item.id); // 使用箭头函数绑定事件
            
            const nameCell = row.insertCell();
            nameCell.textContent = item.name;
            
            const quantityCell = row.insertCell();
            quantityCell.textContent = item.quantity;
            
            const priceCell = row.insertCell();
            priceCell.textContent = `¥${item.price.toFixed(2)}`;

            const subtotalCell = row.insertCell();
            subtotalCell.textContent = `¥${subtotal.toFixed(2)}`;

            const actionCell = row.insertCell();
            actionCell.appendChild(deleteBtn);

            cartTableBody.appendChild(row);
        });
        totalAmountEl.textContent = `¥${total.toFixed(2)}`;
    }

    function addToCart() {
        const productName = productInput.value.trim();
        const quantity = parseInt(quantityInput.value, 10);
        if (!productName || !quantity || quantity <= 0) return alert('请输入有效的商品和数量。');
        
        const product = allProducts.find(p => p.name.toLowerCase() === productName.toLowerCase());
        if (!product) return alert('未找到该商品。');

        const existingItem = shoppingCart.find(item => item.id === product.id);
        if (existingItem) {
            existingItem.quantity += quantity;
        } else {
            shoppingCart.push({ id: product.id, name: product.name, price: product.price, quantity: quantity });
        }
        
        renderCart();
        productInput.value = '';
        quantityInput.value = 1;
        productInput.focus();
    }

    function removeFromCart(productId) {
        shoppingCart = shoppingCart.filter(item => item.id !== productId);
        renderCart();
    }

    function resetCart() {
        shoppingCart = [];
        renderCart();
    }

    async function checkout() {
        if (shoppingCart.length === 0) return alert('购物车为空，无法结账。');
        
        const cashierName = userInfoEl?.textContent || '未知收银员';
        let successCount = 0;
        let transactionTotalPrice = 0;
        let transactionTotalItems = 0;

        for (const item of shoppingCart) {
            try {
                const itemTotalPrice = item.price * item.quantity;
                const response = await fetch(`${BASE_URL}/api/sale_create`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        name: item.name,
                        amount: item.quantity,
                        total_price: itemTotalPrice,
                        cashier: cashierName,
                        date: new Date().toISOString()
                    })
                });
                if (response.ok) {
                    successCount++;
                    transactionTotalPrice += itemTotalPrice;
                    transactionTotalItems += item.quantity;
                }
            } catch (error) {
                console.error(`结账时处理商品 "${item.name}" 发生网络错误:`, error);
            }
        }
        
        if (successCount > 0) {
            salesEl.textContent = (parseFloat(salesEl.textContent) + transactionTotalPrice).toFixed(2);
            ordersEl.textContent = parseInt(ordersEl.textContent, 10) + successCount;
            itemsEl.textContent = parseInt(itemsEl.textContent, 10) + transactionTotalItems;
        }

        alert(successCount === shoppingCart.length ? '结账成功！' : `结账部分成功，有 ${shoppingCart.length - successCount} 项失败。`);
        resetCart();
    }

    // --- 事件绑定 ---
    function bindEvents() {
        if (addToCartBtn) addToCartBtn.addEventListener('click', addToCart);
        if (checkoutBtn) checkoutBtn.addEventListener('click', checkout);
        if (resetCartBtn) resetCartBtn.addEventListener('click', resetCart);
    }

    // --- 页面启动函数 ---
    async function init() {
        console.log('[诊断] 页面初始化开始...');
        if(userInfoEl) userInfoEl.textContent = 'Admin';
        
        bindEvents();

        try {
            const response = await fetch(`${BASE_URL}/api/commodity_getall`);
            if (!response.ok) throw new Error('无法加载商品列表');
            const productData = await response.json();
            allProducts = Array.isArray(productData) ? productData : (productData.data || []);
        } catch (error) {
            console.error('[诊断] 错误：加载商品列表失败。', error);
        }

        await updateStats();
        console.log('[诊断] 页面初始化完成。');
    }

    // --- 启动 ---
    init();
});